<template>
  <!-- 联想建议 -->
  <div class="search-suggestion">
      <van-cell  
        icon="search" 
        v-for="(item,index) in suggestion" 
        :key="index"
        @click="$emit('search',item)"
      >
         <div slot="title" v-html="highlight(item)"></div>
      </van-cell>
  </div>
</template>
<script>
import { getSearchSuggestion } from '@/api/search.js'
import {debounce} from 'lodash' //防抖节流插件

//函数防抖
// const fn=_.debounce(function(){
//    console.log('hello')
// },1000)
// fn()
export default {
  name: 'SearchSuggestion',
  props:{
    searchText:{
      type:String,
      required:true
    }
  },
  computed:{

  },
  components: { },
  directives: {  },
  data() {
    return {
       suggestion:[],
       htmlStr:'hello <span>哈哈</span>'
    };
  },

  mounted() {
    
  },

  methods: {
    highlight(str){
      //new RegExp(this.searchText,'gi') //正则表达式的构造函数
     return str.replace(new RegExp(this.searchText,'gi') ,`<span style="color:red">${this.searchText}</span>`)
    }
  },
  watch:{
    //属性名:要监视的数据的名称
    searchText:{
       handler:debounce(async function(){
        //找到数据接口
        const {data} = await  getSearchSuggestion(this.searchText)
        console.log(data)
        //请求获取数据
        this.suggestion=data.data.options
        //模板绑定展示
      },200),
      immediate: true //该回调将会再侦听开始之后被立即调用
    }
  }
};
</script>
<style lang="less" scoped>

</style>
